<template>
  <div id="doc">
    <div class="row">
      <div class="col-md-3" >
        <div v-for="(cate, cateId) in cates" class="list-group" :key="cateId">
          <div @click="taggleItem(cate)" @contextmenu.stop.prevent="rightClick($event, cateId, 'cate')"
            class="list-group-item list-group-first"
            :class="{active: selectListItem === cate.id}">
            <i class="glyphicon" :class="[cate.glyphicons]"></i>
            <span v-text="cate.name"></span>
            <span class="badge">{{ cate.id }}</span>
          </div>
          <transition-group name="fade"
            enter-active-class="fadeIn"
            leave-active-class="fadeOut">
            <div @click="getCateDetail(childItem)" @contextmenu.stop.prevent="rightClick($event, childItem.id, 'api')"
              v-show="selectListItem === cate.id"
              v-for="(childItem, k) in cate.children" class="list-group-item animated" :key="k"
              :class="{'list-active': selectChild.id === childItem.id}">{{ childItem.name }}
              <span class="badge">{{ childItem.id }}</span>
            </div>
          </transition-group>
        </div>
      </div>
      <div class="col-md-9">
        <blockquote class="panel-primary small bg-info">
          <el-input type="text" v-model="baseUrl" size="small" class="w50">
            <template slot="append">
              <span v-text="indexUrl"></span>
            </template>
          </el-input>
          <span class="navInfo" v-text="navInfo"></span>
        </blockquote>
      </div>
      <div class="col-md-9">
        <table v-for="(item, k) in docDetail"  @contextmenu.stop.prevent="rightClick($event, item.id, 'apiDetail')" :key="k"
          class="table table-striped table-bordered table-hover">
          <thead>
            <tr @click="taggleApi(item)" class="first-tr">
              <td width="10%">
                <strong>功能</strong>
                <span class="sc-text-99" v-text="jobSchedule(item.job_schedule)"></span>
              </td>
              <td width="60%"><span>[{{ item.api_cate_id }}-{{ item.id }}] {{ item.name }}</span></td>
              <td>需登陆[{{ item.need_login | needLogin }}]</td>
            </tr>
          </thead>
          <tbody v-show="testApiItem.id == item.id">
            <tr>
              <td><strong>路径</strong></td>
              <td v-text="item.ver + '/' + item.module + '/' + item.controller + '/' + item.action"></td>
              <td>path</td>
            </tr>
            <!-- <tr>
              <td><strong>微服务</strong></td>
              <td v-text="item.ver"></td>
              <td>ver</td>
            </tr>
            <tr>
              <td><strong>模块</strong></td>
              <td v-text="item.module"></td>
              <td>module</td>
            </tr>
            <tr>
              <td><strong>控制器</strong></td>
              <td v-text="item.controller"></td>
              <td>controller</td>
            </tr>
            <tr>
              <td><strong>方法名</strong></td>
              <td v-text="item.action"></td>
              <td>action</td>
            </tr> -->
            <tr>
              <td><strong>textData</strong></td>
              <td><textarea class="form-control" rows="5" v-model="item.text_data"></textarea></td>
              <td><p class="text-data-info" v-text="item.text_data_info"></p></td>
            </tr>
            <tr>
              <td><strong>令牌</strong></td>
              <td><input class="token" v-model="token"></td>
              <td>token</td>
            </tr>
            <tr>
              <td><strong>测试</strong></td>
              <td v-text="item.testType"></td>
              <td>
                <button @click.self.stop.prevent="test(item)" class="umar-r">发送</button>
                <button @click="clear(item)" class="umar-r">清除</button>
                <button @click="fold(item)" v-text="item.foldType"></button>
              </td>
            </tr>
            <tr>
              <td><strong>发送</strong></td>
              <td colspan="2">
                <div>
                  <pre v-if="item.foldType === '折叠'" v-text="item.sendData"></pre>
                  <pre v-else>{}</pre>
                </div>
              </td>
            </tr>
            <tr>
              <td><strong>返回</strong></td>
              <td colspan="2">
                <pre v-if="item.foldType === '折叠'" v-text="item.testResponse"></pre>
                <pre v-else>{}</pre>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div id="right-click" ref="rightClick">
      <ul>
        <li v-if="showRightProupFlag === 'cate'" @click="createOneCate">创建顶级分类</li>
        <li v-if="showRightProupFlag === 'cate'" @click="removeCate(1)">删除顶级分类</li>
        <li v-if="showRightProupFlag === 'cate'" @click="createTwoCate">创建二级分类</li>
        <li v-if="showRightProupFlag === 'api'" @click="removeCate(2)">删除二级分类</li>
        <li v-if="showRightProupFlag === 'api'" @click="createApi">创建接口文档</li>
        <li v-if="showRightProupFlag === 'apiDetail'" @click="editApi">编辑此接口文档</li>
        <li v-if="showRightProupFlag === 'apiDetail'" @click="removeApi">删除此接口文档</li>
        <li @click="closeProup">关闭</li>
      </ul>
    </div>
  </div>
</template>
<script>
  import router from '../router'
  import md5 from 'blueimp-md5'
  import qs from 'qs'
  import bus from '../assets/js/bus.js'
  import {baseUrl, indexUrl, cateDetailUrl, cateUrl, countUrl, romoveCateUrl, removeApiUrl, tokenUrl} from '../assets/js/setting.js'
  import mixin from '../assets/js/mixin.js'

  export default{
    created () {
      this.getToken()
      this.getCate()
      this.getCount()
      bus.$on('changeBaseUrl', this.changeBaseUrl)
    },
    data: () => {
      return {
        token: '',
        cates: {},
        // 选中项
        selectListItem: {},
        selectChild: {},
        navInfo: '',
        docDetail: [],
        baseUrl: baseUrl,
        indexUrl: indexUrl,
        cateUrl: cateUrl,
        countUrl: countUrl,
        cateDetailUrl: cateDetailUrl,
        romoveCateUrl: romoveCateUrl,
        // 测试的接口
        testApiItem: '',
        testResponse: {},
        sendData: {},
        // 从哪个分类建立
        createCateFromOneId: -1,
        setTimeoutLock: null,
        // 展示哪些子菜单的操作
        showRightProupFlag: ''
      }
    },
    filters: {
      needLogin (val) {
        return (val === '1' || val === 1) ? '是' : '否'
      }
    },
    watch: {
      '$route': {
        handler (to, from) {
          this.getCate()
        },
        deep: true
      }
    },
    mixins: [mixin],
    methods: {
      // 创建一级分类
      createOneCate () {
        if (this.createCateFromOneId !== -1) {
          router.push({path: '/addCate/1/' + this.createCateFromOneId})
        }
        this.closeProup()
      },
      // 删除分类
      removeCate (level) {
        if (this.createCateFromOneId !== -1) {
          // 进行操作
          let loading = this.$loading({fullscreen: true, text: '正在删除分类...'})
          this.$http.post((this.baseUrl + this.romoveCateUrl), qs.stringify({id: this.createCateFromOneId}))
          .then((response) => {
            // console.log('respose:', respose)
            loading.close()
            if (response.status === 200) {
              if (response.data.status === 1) {
                this.$message({
                  message: response.data.msg,
                  type: 'success'
                })
                this.getCate()
              } else {
                this.$message({
                  message: response.data.msg,
                  type: 'warning'
                })
              }
            } else {
              this.$message({
                message: '网络错误:' + response.data.status,
                type: 'error'
              })
            }
            console.log(response)
          })
          .catch((error) => {
            loading.close()
            this.$message({
              message: '错误:' + JSON.stringify(error),
              type: 'error'
            })
          })
          // console.log('删除分类:', this.createCateFromOneId)
        }
        this.closeProup()
      },
      // 创建二级分类
      createTwoCate () {
        if (this.createCateFromOneId !== -1) {
          router.push({path: '/addCate/2/' + this.createCateFromOneId})
        }
        this.closeProup()
      },

      // 创建接口文档
      createApi () {
        if (this.createCateFromOneId !== -1) {
          router.push({path: '/addApi/' + this.createCateFromOneId})
        }
        this.closeProup()
      },
      // 关闭弹出层
      closeProup () {
        this.createCateFromOneId = -1
        this.showRightProupFlag = ''
        this.$refs.rightClick.style.display = 'none'
      },
      // 右击事件
      rightClick (event, cateId, flag) {
        if (event.button === 2) {
          this.showRightProupFlag = flag
          this.createCateFromOneId = cateId
          clearTimeout(this.setTimeoutLock)
          let e = event || window.event
          let scrollX = document.documentElement.scrollLeft || document.body.scrollLeft
          let scrollY = document.documentElement.scrollTop || document.body.scrollTop
          let x = e.pageX || e.clientX + scrollX
          let y = e.pageY || e.clientY + scrollY
          this.$refs.rightClick.style.left = x + 'px'
          this.$refs.rightClick.style.top = y + 'px'
          this.$refs.rightClick.style.display = 'block'
          this.setTimeoutLock = setTimeout(this.closeProup, 5000)
        }
      },
      // 创建api_key
      _createApiKey (send) {
        send.sendTime = (Date.parse(new Date()) + '').substring(0, 10)
        send.ver || (send.ver = 'ver1')
        send.encryption || (send.encryption = 'off')
        send.expiry || (send.expiry = 0)
        let keyA = send.sendTime.substring(0, 5)
        let keyB = send.sendTime.substring(5, 10)
        send.token = this.token
        send.appkey = md5(send.ver + keyA + send.encryption + send.module + keyB + send.controller + send.action + send.token)
        return send
      },
      // 测试按钮
      test (item) {
        let res = this._createApiKey(item)
        item.sendData = {
          appkey: res.appkey,
          sendTime: res.sendTime,
          ver: res.ver,
          module: res.module,
          controller: res.controller,
          action: res.action,
          encryption: res.encryption,
          textData: res.text_data,
          token: res.token
        }
        item.testType = '已发送数据...'
        let loading = this.$loading({fullscreen: true, text: '正在请求接口...'})
        this.$http.post((this.baseUrl + this.indexUrl), qs.stringify(item.sendData))
        .then((response) => {
          loading.close()
          if (response.status === 200) {
            if (item.sendData.controller === 'ApiUser' && item.sendData.action === 'login') {
              bus.$emit('testLogin', response.data)
            } else if (item.sendData.controller === 'ApiUser' && item.sendData.action === 'logout') {
              bus.$emit('testLogout', response.data)
            }
            item.testResponse = response.data
            item.testType = response.data.msg
            if (response.data.status === 1) {
              this.$message({
                message: response.data.msg,
                type: 'success'
              })
            } else {
              if (response.data.status === -2) {
                bus.$emit('testLogout', response.data)
              }
              this.$message({
                message: response.data.msg,
                type: 'warning'
              })
            }
            console.log('testResponse', item.testResponse)
          } else {
            alert(JSON.stringify(response))
            console.log('response', response)
          }
        })
        .catch((error) => {
          loading.close()
          alert(JSON.stringify(error))
          console.log(error)
        })
      },
      // 清除
      clear (item) {
        item.sendData = {}
        item.testResponse = {}
        item.testType = '已清除数据...'
      },
      // 折叠展开
      fold (item) {
        item.foldType = (item.foldType === '折叠' ? '展开' : '折叠')
      },
      // 展示关闭测试窗口
      taggleApi (item) {
        if (this.testApiItem.id === item.id) {
          this.testApiItem = ''
        } else {
          this.testApiItem = item
        }
      },
      // 获取分类的详情
      getCateDetail (item) {
        this.selectChild = item
        let loading = this.$loading({fullscreen: true, text: '正在载入子分类数据...'})
        this.$http.get(this.baseUrl + this.cateDetailUrl, {params: {id: item.id}})
        .then((response) => {
          loading.close()
          if (response.data.status === 1) {
            for (var i = 0; i < response.data.res.length; i++) {
              response.data.res[i].sendData = {}
              response.data.res[i].testResponse = {}
              response.data.res[i].testType = '未请求接口...'
              response.data.res[i].foldType = '折叠'
            }
            this.docDetail = response.data.res
            this.$message({
              message: response.data.msg,
              type: 'success'
            })
          } else {
            this.navInfo = response.data.msg
            this.$message({
              message: response.data.msg,
              type: 'warning'
            })
          }
        })
        .catch((error) => {
          loading.close()
          console.log(error)
        })
      },
      // 返回状态
      jobSchedule (val) {
        let str = ''
        switch (val) {
          case '0':
          case 0:
            str = '未做'
            break
          case '1':
          case 1:
            str = '完成'
            break
          case '-1':
          case -1:
            str = '废弃'
            break
          case '-2':
          case -2:
            str = '开发'
            break
          default:
            str = '未知'
        }
        return str
      },
      // 获取一个token
      getToken () {
        this.$http.post(this.baseUrl + tokenUrl)
        .then((response) => {
          if (response.data.status !== 1 || response.data.res[0].res.token.length !== 32) {
            this.$message({
              message: response.data.res[response.failureIndex].msg,
              type: 'warning'
            })
          } else {
            this.token = response.data.res[0].res.token
          }
        })
        .catch((e) => {
          console.log('e', e)
        })
      },
      // 获取分类信息
      getCate () {
        let loading = this.$loading({fullscreen: true, text: '正在载入分类数据...'})
        this.$http.post(this.baseUrl + this.cateUrl)
        .then((response) => {
          loading.close()
          if (response.data.status === 1) {
            this.cates = response.data.res
            this.$message({
              message: response.data.msg,
              type: 'success'
            })
          } else {
            this.navInfo = response.data.msg
            this.$message({
              message: response.data.msg,
              type: 'warning'
            })
          }
          console.log(response)
        })
        .catch((error) => {
          loading.close()
          console.log(error)
        })
      },
      // 获取统计信息
      getCount () {
        this.$http.post(this.baseUrl + this.countUrl)
        .then((response) => {
          if (response.data.status === 1) {
            let count = 0
            let info = ''
            // console.log('response:', response.data.res)
            for (var i = 0; i < response.data.res.length; i++) {
              info += '[' + this.jobSchedule(response.data.res[i].job_schedule) + ']' + response.data.res[i].sum + '个 '
              count += parseInt(response.data.res[i].sum)
            }
            this.navInfo = '接口总数:' + count + ' ' + info + '!'
            // console.log(info)
          } else {
            alert(response.data.msg)
          }
        })
        .catch((error) => {
          console.log(error)
        })
      },
      // 切换标题
      taggleItem (item) {
        if (this.selectListItem === item.id) {
          this.selectListItem = ''
        } else {
          this.selectListItem = item.id
        }
      },
      // 编辑此接口文档
      editApi () {
        let id = this.createCateFromOneId
        // 跳到新路由
        console.log('编辑此接口文档' + id)
      },
      // 删除此接口文档
      removeApi () {
        if (!confirm('你确定删除此接口文档?')) {
          return
        }
        let id = this.createCateFromOneId
        // 发送请求
        this.$http.get(removeApiUrl, {params: {id: id}})
        .then(response => {
          if (response.status === 200) {
            if (response.data.status === 1) {
              let len = this.docDetail.length
              let newApis = []
              for (let i = 0; i < len; i++) {
                if (this.docDetail[i].id !== id) {
                  newApis.push(this.docDetail[i])
                }
              }
              this.docDetail = newApis
            } else {
              this.$message({
                message: response.data.msg,
                type: 'warning'
              })
            }
          } else {
            console.log('删除此接口文档then-error:', response)
          }
        })
        .catch(error => {
          console.log('删除此接口文档error:', error)
        })
      }
    }
  }
</script>
<style scoped>
  #doc{
    margin-top: 60px;
  }
  .list-group{
    margin-bottom: 4px;
  }
  .glyphicon{
    margin-right: 10px;
  }
  .list-group-first{
    border-left: 4px solid #337AB7;
  }
  .list-active{
    border-left: 4px solid #FFC90E;
  }
  .first-tr{
    background: #D9EDF7 !important;
    border-left: 4px solid #337AB7;
  }
  pre{
    max-width: 750px;
  }
  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
  }
  .fade-enter, .fade-leave-active {
    opacity: 0;
  }
  #right-click{
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1000;
    width: 200px;
    border: 1px solid #CCC;
    background: rgba(0,0,0,0.7);
    color: #FFF;
    border-radius: 5px;
    display: none;
  }
  #right-click > ul{
    list-style: none;
    padding: 0;
    margin: 0;
  }
  #right-click > ul > li{
    line-height: 2.5em;
    border-bottom: 1px solid #CCC;
    text-align: center;
  }
  #right-click > ul > li:hover{
    color: yellow;
  }
  #right-click > ul > li:last-child{
    border-bottom: none;
  }
  .navInfo{
    margin-left: 2em;
    color: #999;
  }
  .text-data-info{
    max-width: 200px;
  }
  .umar-r{
    margin-right: 0.5em;
  }
  .sc-text-99{
    color: #999;
  }
  .w50{
    width: 50%;
  }
  .token{
    width: 500px;
  }
</style>
